package com.onLineCar.management.service.impl;

import com.alibaba.fastjson.JSON;
import com.onLineCar.common.core.domain.Result;


import com.onLineCar.management.domain.*;

import com.onLineCar.management.domain.request.ContractRequest;
import com.onLineCar.management.domain.request.OrderRequest;
import com.onLineCar.management.domain.request.RequestOrders;
import com.onLineCar.management.service.PlaceAnOrderService;
import com.onLineCar.management.template.*;


import com.onLineCar.management.utils.WordExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.onLineCar.management.config.UniformConstant.SUCCESS;

/**
 * @author : 段敏强
 * @className : PlaceAnOrderServiceImpl
 * @description : 描述说明该类的功能
 * @createTime : 2023/12/18 19:46
 */

/**
 * 订单服务实现类
 * @author 段敏强
 *
 */
@Service
public class PlaceAnOrderServiceImpl implements PlaceAnOrderService {


    @Autowired
    private OrderDataFeign orderDataFeign;

    @Autowired
    private QueryCarLevelAllFeign queryCarLevelAllFeign;

    @Autowired
    private DispatchVehicleFeign dispatchVehicleFeign;

    @Autowired
    private QueryDriverFeign queryDriverFeign;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HttpServletResponse response;





    /**
     * 订单接口
     * @param orderRequest
     * @return
     */
    @Override
    public String orderInterface(OrderRequest orderRequest) {
        System.out.println(orderRequest);
        Result placeAnOrder = orderDataFeign.getPlaceAnOrder(orderRequest);
        String string = placeAnOrder.getData().toString();
        RequestOrder tblOrder = new RequestOrder();
        tblOrder.setOrderNumber(String.valueOf(tblOrder));
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderNum(Long.valueOf(string));
        orderDTO.setOrderTime(orderRequest.startTime);
        orderDTO.setOrderType(orderRequest.getLevelId());
        orderDTO.setUseCarTime(orderRequest.getTimeInCar());
//        dispatchVehicleFeign.getDispatchVehicleData(orderDTO);
        if (placeAnOrder.getCode() == SUCCESS) {
            return string;
        }
        return null;
    }

    /**
     * 查询所有车型
     * @return
     */
    @Override
    public List<VehicleLevel> queryCarLevelAll() {
        return queryCarLevelAllFeign.getQueryCarLevelAll();
    }

    /**
     * 根据订单id查询订单
     * @param id
     * @return
     */
    @Override
    public RequestOrder getSelectByUserId(String id) {
        // 检查Redis中是否存在指定id的键
        if (redisTemplate.hasKey(id)){
            // 如果存在，则获取该键对应的值，并返回
            String s = redisTemplate.opsForValue().get(id);
            return  JSON.parseObject(s, RequestOrder.class);
        }

        // 通过FeignClient调用服务端获取指定id的订单
        RequestOrder selectByUserId = orderDataFeign.getSelectByUserId(id);

        // 将获取到的订单存储到Redis中，设置过期时间为1天

        redisTemplate.opsForValue().set(id,JSON.toJSONString(selectByUserId),1, TimeUnit.DAYS);

        // 返回获取到的订单
        return selectByUserId;

    }

    @Override
    public String getOrderNumber() {
        return orderDataFeign.getOrderNumber();
    }


    /**
     * 合同
     * @param contractRequest
     */
    @Override
    public void contract(ContractRequest contractRequest) {
        try {
            new WordExportService().exportWord(response,contractRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        try {
//
//
//            File file = ResourceUtils.getFile("classpath:template/laborContract.docx");
//            FileInputStream stream = new FileInputStream(file);
//            InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("ContractTemplate.docx");
//            System.out.println(stream);
//            FileInputStream fileInputStream = new FileInputStream(file);
//            String outputPath = "C:\\Users\\Administrator\\Desktop\\output.docx";
//
//            XWPFTemplate template = XWPFTemplate.compile(resourceAsStream);
//
//            HashMap<String, String> map = new HashMap<>();
//
//            Field[] declaredFields = contractRequest.getClass().getDeclaredFields();
//
//            Class<ContractRequest> aClass = ContractRequest.class;
//            Field[] fields = aClass.getDeclaredFields();
//            for (Field declaredField : declaredFields) {
//                for (Field field : fields) {
//                    if (null == declaredField){
//                        map.put(String.valueOf(field),"/");
//                    }else {
//                        map.put(String.valueOf(field),declaredField.getName());
//                    }
//                }
//
//            }
//            StringSubstitutor stringSubstitutor = new StringSubstitutor(map);
//            stringSubstitutor.replace(map);
//            FileOutputStream outputStream = new FileOutputStream(outputPath);
//            template.write(outputStream);
//            outputStream.close();
//            System.out.println("生成的文档已保存。");
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }


    }

    /**
     * 更新用户到达
     * @param orderNumber
     */
    @Override
    public void updateUserReach(String orderNumber) {
        orderDataFeign.getUpdateUserReach(orderNumber);
    }




    /**
     * 取消订单
     * @param tblOrder
     */
    @Override
    public void cancelAnOrder(RequestOrders tblOrder) {
        orderDataFeign.getCancelOrder(tblOrder);
    }
}
